package org.zhaya.sdk.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author ：nemo.fang
 * @date ：Created in 2022/3/15 16:14
 * @description：Jackson工具类
 * @version:
 */
@Slf4j
public class JacksonUtil {
    private static final JsonMapper OBJECT_MAPPER = JsonMapper.builder()
            //反序列化数据中有多余的属性不报错
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            //不使用科学技术
            .enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN)
            .serializationInclusion(JsonInclude.Include.NON_DEFAULT)
            .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .defaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.ALWAYS, JsonInclude.Include.NON_NULL))
            .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
            .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
            .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
            .enable(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)
            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
            .enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS)
            .addModules(new AfterburnerModule())
            .disable(SerializationFeature.WRITE_NULL_MAP_VALUES)
            .serializationInclusion(JsonInclude.Include.NON_NULL)
            .build();


    public static String toJSONString(Object o) {
        String result = null;
        try {
            result = OBJECT_MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
        }
        return result;
    }

    /**
     * 转换为 JavaBean
     */
    public static <T> T json2pojo(String jsonString, Class<T> clazz) throws JsonProcessingException {
        OBJECT_MAPPER.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return OBJECT_MAPPER.readValue(jsonString, clazz);
    }

    private static final ObjectMapper MAPPER = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

    /**
     * 字符串转换为 Map<String, Object>
     */
    public static Map<String, Object> json2map(String jsonString) throws Exception {
        return MAPPER.readValue(jsonString, Map.class);
    }

}
